<template>
  <master title="图片管理">
    <!-- Author: guyang -->
    <!-- 需要新增子页面，考试学生，成绩 -->
    <!-- 顶部布局 -->
    <div class="searchForm">
      <!-- 搜索组 -->
      <!-- <div class="searchFormInputs">
        <el-input class="searchFormInput" v-model="params.name" placeholder="名称"></el-input>
      </div> -->
      <!-- 顶部按钮 -->
      <!-- <div class="searchFormInputs">
        <el-button type="primary" icon="el-icon-search" @click="searchList">查询</el-button>
      </div> -->
      <div class="searchFormInputs">
        <!-- <div class="searchFormInputs" v-if="adminUser"> -->
        <el-button type="danger" icon="el-icon-plus" @click="edit()">增加</el-button>
      </div>
    </div>
    <!-- 列表数据 -->
    <div class="el-table" style="width: 98%;margin: 0;">
      <el-table :data="rows" stripe>
        <!-- <el-table-column prop="name" label="名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="addr" label="地址" header-align="center" align="center"></el-table-column>
        <el-table-column prop="price" label="报名费" header-align="center" align="center"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" header-align="center" align="center"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" header-align="center" align="center"></el-table-column> -->
        <!-- <el-table-column prop="introduction" label="简介" header-align="center" align="center"></el-table-column> -->
        <el-table-column prop="type" label="类型" header-align="center" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">图片</div>
            <div v-if="scope.row.type==2">视频</div>
          </template>
        </el-table-column>
        <el-table-column prop="img" label="图片" header-align="center" align="center">
          <template slot-scope="scope">
            <image class="iimage" mode="heightFix" :src="scope.row.img"></image>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column prop="rows" header-align="center" align="center" class="table1" label="操作">
          <template slot-scope="scope" class="table1">
            <div class="table1">
              <div style="margin-left: 10px;">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(scope.row)">修改</el-button>
              </div>
              <!-- <div style="margin-left: 10px;">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="detail(scope.row)">详情</el-button>
              </div> -->
              <div style="margin-left: 10px;">
                <el-button type="primary" size="mini" icon="el-icon-delete" @click="deletea(scope.row)">删除</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page1">
      <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="params.pageNum"
        :page-sizes="[10, 100, 200, 300, 400]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 编辑和新增组件 -->
    <el-dialog class="addAndEdit" :title="editForm.id ? '编辑' : '新增'" :visible.sync="visible">
      <el-form ref="editForm" :model="editForm">
        <div class="row1">
          <div class="msrow">
            <el-form-item class="row marleft" label="类型">
              <el-select v-model="editForm.type" placeholder="请选择">
                <el-option v-for="item in types" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="row marleft" label="图片">
              <el-upload action="/upload" :headers="header" :on-success="upOk" :on-remove="handleRemove" limit="1"
                :on-preview="handlePreview" :on-error="upFail" list-type="picture-card" :auto-upload="true"
                :file-list="fileList">
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </div>
          <el-form-item style="text-align: right;">
            <el-button type="primary" @click="visible = false;fileList=[]">取消</el-button>
            <el-button type="danger" @click="save(editForm.id)">保存</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </master>
</template>
<script type="text/javascript">
  (function (G) {
    var _this;
    G.vue({
      "usingComponents": {//引入组件
        "master": "/components/Master/Master",//母版组件
      },
      "enablePullDownRefresh": true
    }, {
      data: {
        types: [
          { name: '图片', value: '1' },
          { name: '视频', value: '2' }
        ],
        tableApi: '/api/model/pics',
        showdetail: false, // 放大图片
        url: '', // 放大后的url
        adminUser: false,
        header: {},
        units: JSON.parse(G.Storage.get('units', 1)),
        members: JSON.parse(G.Storage.get('members', 1)),
        teachers: JSON.parse(G.Storage.get('teachers', 1)),
        unitInfo: [],
        fileList: [],
        params: {//页面请求参数
          pageSize: 10,
          pageNum: 1,
        },
        rows: [],//列表数据
        gameRegList: [],//列表数据
        total: 0,//总数据量
        visible: false, // 新增和编辑弹窗
        visible1: false, // 详情弹窗
        editForm: {},//新增或者编辑的时候传入弹窗的值
      },
      // ******************method**********************
      methods: {
        detailConfirm(row) { // 修改赛事结果
          if (this.fileList.length == 0) {
            this.$message.error('请上传结果');
          } else {
            console.log('this.fileList', this.fileList);
            row.result = this.fileList.map(item => item.url);
            G.put(this.tableApi, row).then((res) => {
              if (!res.errorMsg) {
                this.params = {
                  pageSize: 10,
                  pageNum: 1,
                }
                this.$message.success('修改成功');
                this.getList();
              } else {
                this.$message.error(res.errorMsg);
              }
            })
          }
        },
        upOk(res, file, fileList) {// 上传图片成功
          console.log('上传', res, file, fileList);
          this.fileList = fileList.map(item => {
            if (item.response && item.response.id) {
              return {
                url: `/file/${item.response.id}`,
                uid: `/file/${item.response.id}`
              };
            } else {
              return item;
            }
          });
          console.log('this.fileList', this.fileList);
        },
        handleRemove(file, fileList) {
          console.log(file, fileList);
          if (fileList.length == 0) {
            this.fileList = []
          } else {
            this.fileList = fileList.map(item => {
              return "/file/" + item.response.id
            })
          }
        },
        upFail(err, file, fileList) {// 上传图片失败
          console.log('fileList fail:', err, file, fileList);
          this.$message({
            type: 'info',
            message: '上传失败：',
          });
        },
        handlePreview(file) { // 点击放大
          console.log('handlePreview', file);
          this.url = file.url
          this.showdetail = this.showdetail == true ? false : true
        },
        save(id) {
          if (this.fileList.length == 0) {
            this.$message.error('请上传图片');
          } else {
            this.editForm['img'] = this.fileList[0].url
            if (id) {
              G.put(this.tableApi, this.editForm).then((res) => {
                if (!res.errorMsg) {
                  this.visible = false;
                  this.fileList = []
                  this.params = {
                    pageSize: 10,
                    pageNum: 1,
                  }
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.getList();
                } else {
                  this.$message.error(res.errorMsg);
                }
              })
            } else {
              G.post(this.tableApi, this.editForm).then((res) => {
                if (!res.errorMsg) {
                  this.visible = false;
                  this.params = {
                    pageSize: 10,
                    pageNum: 1,
                  }
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  });
                  this.getList();
                } else {
                  this.$message.error(res.errorMsg);
                }
              })
            }
          }
        },
        deletea(row) {// 拒绝弹窗
          this.$confirm('确定删除吗？', '删除提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            G.delete(this.tableApi, {
              id: row.id
            }).then(res => {
              if (!res.errorMsg) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '删除成功',
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
        },
        edit(row) { // 编辑按钮
          console.log('row', row);
          this.editForm = row ? row : {}
          this.fileList = row ? [{ uid: row.img, url: row.img }] : []
          console.log('this-------------.fileList', this.fileList);
          this.visible = true
        },
        changeScroe(row) { // 修改成绩
          console.log('row', row);
          this.$confirm('确定修改吗？', '修改提醒', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 修改报名记录里面的积分
            G.put('/api/model/gameReg', row).then(res => {
              if (!res.errorMsg) {
                // 查询用户积分
                G.get('/api/model/member', { id: row.userId }).then(res2 => {
                  if (!res2.errorMsg) {
                    let param = {}
                    param.id = row.userId
                    param.score = parseInt(row.score) + parseInt(res2.score)
                    // 修改用户积分
                    G.put('/api/model/member', param).then(res1 => {
                      if (!res1.errorMsg) {
                        // 添加积分记录
                        let param1 = {}
                        param1.userId = row.userId
                        param1.score = row.score
                        param1.type = 4
                        param1.role = 2
                        G.post('/api/model/psrecord', param1).then(res3 => {
                          if (!res3.errorMsg) {
                            this.$message({
                              type: 'success',
                              message: '修改成功',
                            });
                          } else {
                            this.$message({
                              type: 'error',
                              message: res1.errorMsg,
                            });
                          }
                        })
                      } else {
                        this.$message({
                          type: 'error',
                          message: res1.errorMsg,
                        });
                      }
                    })
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.errorMsg,
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
        },
        detail(row) { // 详情按钮
          console.log(row);
          if (row.result == null) {
            this.fileList = []
          } else {
            this.fileList = []
            let imgs = row.result.split(',')
            imgs.forEach(item => {
              this.fileList.push({ url: item, uid: item })
            })
          }
          console.log('this.fileList', this.fileList);
          let patams = {}
          patams.gameId = row.id
          patams.unitId = { $regex: 'motorcycle' + '.*?' }
          G.get('/api/model/gameReg', patams).then(res => {
            if (!res.errorMsg) {
              this.editForm = row ? row : {}
              this.visible1 = true
              res.forEach(p => {
                const item2 = this.members.find(item => item.id === p.userId);
                console.log('-----item2:', item2);
                if (item2) {
                  p.userName = item2.name
                  const item3 = this.units.find(item => item.unitId === item2.unitId);
                  console.log('-----item3:', item3);
                  if (item3) {
                    p.unitName = item3.name
                  }
                }
              })
              this.gameRegList = res
              console.log(res);

            } else {
              this.$message({
                type: 'error',
                message: res.errorMsg,
              });
            }
          })
        },
        sizeChange(pageSize) {
          this.params.pageSize = pageSize;
          this.params.pageNum = 1;
          this.getList();
        },
        currentChange(pageNum) {
          this.params.pageNum = pageNum;
          this.getList();
        },
        searchList() {
          let name = this.params.name
          let addr = this.params.addr
          let startTime = this.params.startTime
          let endTime = this.params.endTime
          if (this.params.name) {
            this.params.name = { $regex: '.*?' + name + '.*?' }
          }
          if (this.params.addr) {
            this.params.addr = { $regex: '.*?' + addr + '.*?' }
          }
          if (this.params.startTime) {
            this.params.startTime = { $regex: '.*?' + startTime + '.*?' }
          }
          if (this.params.endTime) {
            this.params.endTime = { $regex: '.*?' + endTime + '.*?' }
          }
          ////////////////////////////
          this.params.pageNum = 1;
          this.getList();
          ////////////////////////////
          if (this.params.name) {
            this.params.name = name
          }
          if (this.params.addr) {
            this.params.addr = addr
          }
          if (this.params.startTime) {
            this.params.startTime = startTime
          }
          if (this.params.endTime) {
            this.params.endTime = endTime
          }
        },
        getList() {
          this.header = {
            'token': G.Storage.get('userInfo').token
          };
          G.get('/v1/gameList', this.params).then((res) => {
            if (!res.errorMsg) {
              // res.rows.forEach(item => {
              //   item.showimg = JSON.parse(item.img)[0].url
              // })
              this.rows = res.rows
              this.total = parseInt(res.total)
            }
          })
        },

      },
      // 初始化调用
      mounted() {
        this.params = {//页面请求参数
          pageSize: 10,
          pageNum: 1,
          sql: { sort: { createTime: -1 } },
        }
        this.adminUser = G.Storage.get('userInfo').unitId == 'motorcycle' ? true : false
        this.getList();
        _this = this
      }
    });
  })(Y)
</script>
<style scoped>
  .textCon {
    border: solid 1px gray;
    padding: 10px;
    border-radius: 3px;
    width: 95%;
    line-height: 25px;
  }

  .msrow {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    margin-right: 80px;
    margin-left: 20px;
  }

  .ms {
    font-weight: 700;
    width: 40px;
  }

  .introduction {
    width: 100%;
  }

  .iimage {
    height: 100px;
  }

  .text1row {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    white-space: nowrap;
  }

  .text3row {
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    word-break: break-all;
  }

  .table1 {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .searchFormInputs {
    margin-top: 5px;
  }

  .searchForm {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .row {
    display: flex;
    flex-direction: row;
  }

  .martop20 {
    margin-top: 5px;
  }

  .marleft {
    margin-left: 20px;
  }

  .el-row {
    margin-bottom: 20px;

    /* &:last-child {
      margin-bottom: 0;
    } */
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }

  .center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .we700 {
    font-weight: 400;
    color: black;
  }

  .wrap {
    display: flex;
    flex-wrap: wrap;
  }

  .border1 {
    border: solid 1px;
  }

  .maright {
    margin-right: 20px;
  }

  .ownimg {
    height: 100%;
  }

  .warp {
    display: flex;
    flex-wrap: wrap;
  }

  .clumn {
    display: flex;
    flex-direction: column;
  }
</style>